//created by koa-generator。
const Koa = require('koa')
const app = new Koa()
const check = require('./security')
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const fs = require('fs')
const path = require('path');
//log工具
const log = require('./logUtil');
console.log('start service');

const mr = require('./routes/mr.js')
const dic = require('./routes/dic.js')
const model = require('./routes/model.js')
const config = require('./config.js')

let needSecurity = false

// logger
// app.use(async (ctx, next) => {
//   //响应开始时间
//   const start = new Date();
//   //响应间隔时间
//   var ms;
//   try {
//     //开始进入到下一个中间件
//     await next();

//     ms = new Date() - start;
//     //记录响应日志
//     //log.logResponse(ctx, ms);

//   } catch (error) {

//     ms = new Date() - start;
//     //记录异常日志
//     log.logError(ctx, error, ms);
//   }
// });


// error handler
onerror(app)

//without process.on node will not print error info percessly, only for node
process.on('unhandledRejection', (reason, p) => {
  console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
  // application specific logging, throwing an error, or other logic here
});
// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
if (!config.includeClient)
  app.use(require('koa2-cors')())
app.use(require('koa-static')(__dirname + '/client'))

// app.use(views(__dirname + '/views', {
//   extension: 'pug'
// }))

// main request line
app.use(async (ctx, next) => {
  const start = new Date()
  await next()

  const ms = new Date() - start
  console.log('total spend:' + `${ctx.method} ${ctx.url} - ${ms}ms`)
})

if (needSecurity)
  app.use(check)
//let payload = jwt.verify(token, secret)
// routes
app.use(mr.routes(), mr.allowedMethods())
app.use(dic.routes(), dic.allowedMethods())
app.use(model.routes(), model.allowedMethods())

app.use(async (ctx, next) => {
  ctx.type = 'html';
  ctx.body = await fs.createReadStream(path.resolve(__dirname, '.', 'client', 'index.html'));

})
// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

//app.listen(3000);
module.exports = app